import { useEffect, useState } from 'react';

const Home = () => 'Home';
const Search = () => 'Search';
const Comment = () => 'Comment';

export const RouterHistory = () => {
  // 定义组件状态
  const [path, setPath] = useState(window.location.pathname);

  useEffect(() => {
    const handleUrlChange = (e) => {
      console.log(e);
      console.log('popstate event occurred!', e.target.location.pathname);
      setPath(e.target.location.pathname);
    };

    // 给 window 设置 popstate 事件，
    window.addEventListener('popstate', handleUrlChange);

    // 清理函数
    return () => {
      window.removeEventListener('popstate', handleUrlChange);
    };
  }, []);

  return (
    <div>
      <ul>
        <li>
          <a
            href="/home"
            onClick={(e) => {
              console.log(e);
              e.preventDefault();
              window.history.pushState({}, '', '/home');
              window.dispatchEvent(new Event('popstate'));
            }}
          >
            首页
          </a>
        </li>
        <li>
          <a
            href="/comment"
            onClick={(e) => {
              e.preventDefault();
              window.history.pushState({}, '', '/comment');
              window.dispatchEvent(new Event('popstate'));
            }}
          >
            评论
          </a>
        </li>
        <li>
          <a
            href="/search"
            onClick={(e) => {
              e.preventDefault();
              window.history.pushState({}, '', '/search');
              window.dispatchEvent(new Event('popstate'));
            }}
          >
            搜索
          </a>
        </li>
      </ul>
      {/* 基于url地址栏的条件渲染 */}
      <div>
        {path === '/home' && <Home></Home>}
        {path === '/search' && <Search></Search>}
        {path === '/comment' && <Comment></Comment>}
      </div>
    </div>
  );
};
